﻿using System;
using System.IO;
using System.Linq;
using System.Windows.Media;
using Styx.Common;
using Styx.Plugins; 

namespace CustomProtectedItemInstaller
{
    public class CP2I : HBPlugin
    {
        // Overrides.
        public override string Name { get { return "CP2I"; } }
        public override string Author { get { return "toNyx"; } }
        public override Version Version { get { return new Version(1, 0, 0, 0); } }
        public override bool WantButton { get { return false; } }
        public override void OnButtonPress() { }
        public override string ButtonText { get { return "No Settings"; } }

        // Custom vars
        private static bool _needRestart;
        private static readonly string RootProtectedItemsFilePath = Path.Combine(Utilities.AssemblyDirectory, string.Format("{0}", @"Protected Items.xml"));
        private static readonly string MyProtectedItemsFilePath = Path.Combine(Utilities.AssemblyDirectory, string.Format("{0}", @"Plugins\CustomProtectedItemInstaller\Protected Items.xml"));

        //Logging Class
        public static void Cp2ILog(Color myColor, string msg) { Logging.Write(myColor, "[CP2I] " + msg); }

        public override void OnEnable()
        {
            if (Updater.CheckForUpdate())
                _needRestart = true;
            
            if (!FilesAreEquals())
            {
                try
                {
                    // Will overwrite the shipped PI File if it's not the same as ours.
                    File.Copy(MyProtectedItemsFilePath, RootProtectedItemsFilePath, true);
                    Cp2ILog(Colors.DeepSkyBlue, "Successfully copied the Custom Protected Items file into the root folder !");
                    _needRestart = true;

                    // Stopping the bot to prevent it doing things with the wrong file.
                    //Styx.CommonBot.BotManager.Current.Stop();
                }
                catch (IOException copyError)
                {
                    Cp2ILog(Colors.Red, "Error during the process, with the following error : " + copyError.Message);
                }
            }
            else
            {
                Cp2ILog(Colors.Gold, "The file is already the custom one, have fun !");
            }

            if (_needRestart)
                Cp2ILog(Colors.Plum, "Honorbuddy needs to be restarted in order to make CP2I changes occur. Do it ASAP !");

        }

        public override void Pulse(){ }

        public static bool FilesAreEquals()
        {
            var rootFile = File.ReadAllBytes(RootProtectedItemsFilePath);
            var myFile = File.ReadAllBytes(MyProtectedItemsFilePath);

            if (rootFile.Length == myFile.Length)
                return !rootFile.Where((t, i) => t != myFile[i]).Any();

            return false;
        }

    }
}